package com.github.eclipseace.mybatis.entity.builder.xml;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.session.Configuration;
import org.w3c.dom.Document;

import com.github.eclipseace.mybatis.entity.builder.ElementBuilder;
import com.github.eclipseace.mybatis.entity.mapping.MappedEntity;

/**
 * @author eclipseAce
 */
public class XmlElementBuilder implements ElementBuilder {
	private final XPathParser parser;

	public XmlElementBuilder(String xml) {
		this.parser = new XPathParser(xml);
	}

	public XmlElementBuilder(Reader reader) {
		this.parser = new XPathParser(reader);
	}

	public XmlElementBuilder(InputStream stream) {
		this.parser = new XPathParser(stream);
	}

	public XmlElementBuilder(Document document) {
		this.parser = new XPathParser(document);
	}

	public XmlElementBuilder(ClassLoader classLoader, String location) throws IOException {
		Reader reader = Resources.getResourceAsReader(classLoader, location);
		try {
			this.parser = new XPathParser(reader);
		} finally {
			reader.close();
		}
	}

	@Override
	public List<XNode> getFragments(Configuration configuration, MappedEntity entity) {
		XmlTemplateRenderer renderer = new XmlTemplateRenderer(entity, parser);
		return renderer.render("sql");
	}

	@Override
	public List<XNode> getStatements(Configuration configuration, MappedEntity entity) {
		XmlTemplateRenderer renderer = new XmlTemplateRenderer(entity, parser);
		return renderer.render("select|insert|update|delete");
	}
}
